package com.xxgc.cloud.error.center.error;

import com.xxgc.cloud.error.center.GlobalException;
import com.xxgc.cloud.error.center.result.ErrResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * @program: SpringCloudStudy
 * @description: SpringMvc相关错误
 * @author: Mr.abel(ShiJiaYi)
 * @create: 2022-11-23 16:13
 **/
@Slf4j
@ControllerAdvice
@ResponseBody
public class SpringMvcException extends GlobalException {
    //参数校验错误
    @ExceptionHandler(value = {
            MethodArgumentNotValidException.class,
    })
    public ErrResult<MethodArgumentNotValidException> methodArgumentNotValidException(MethodArgumentNotValidException e){
        String msg = active.equals(myActive) ? system : e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        // 参数校验比较特殊，不需要返回详参
        return active.equals(myActive) ? ErrResult.error(msg, METHODARGUMENTNOTVALID_CODE) : ErrResult.error(msg, METHODARGUMENTNOTVALID_CODE);
    }

    @ExceptionHandler(value = {
            ConstraintViolationException.class //手机号校验会报这个
    })
    public ErrResult<ConstraintViolationException> methodArgumentNotValidException(ConstraintViolationException e){
        String msg = active.equals(myActive) ? system : e.getMessage().substring(e.getMessage().indexOf(":")+1).trim();
        // 参数校验比较特殊，不需要返回详参
        return active.equals(myActive) ? ErrResult.error(msg, METHODARGUMENTNOTVALID_CODE) : ErrResult.error(msg, METHODARGUMENTNOTVALID_CODE);
    }
}
